from fastapi import APIRouter, Header, Depends

from pydantic.main import BaseModel

from api import ok, mysql
from const import tbl__market_industryOverview

router = APIRouter()

class SaveForm(BaseModel):
    name = ''
    age = ''

class UpdateForm(BaseModel):
    name = ''
    age = ''

@router.get('/', summary='首页')
def index():
    userList = [user for user in User.select()]
    return ok(data={'result': userList})

@router.post('/save', summary='保存')
def save(form:SaveForm):
    print('参数form', form)
    user = User.create(name = form.name, age = form.age)
    return ok(data={'op': 'save', 'user':user})

@router.get('/search/{id}', summary='搜索')
def search(id: int):
    print('参数id', id)
    user = User.get_or_none(User.id == id)
    print('结果', user.id, user.name, user.age)
    return ok(data={'op': 'search', 'result':user})

@router.put('/update/{id}', summary='修改')
def update(id:int, form:UpdateForm):
    print('参数id', id, '参数form', form)
    user = User.get_by_id(id)
    user.name = form.name
    user.save()
    return ok(data={'op': 'update'})

###################################################################################################################

from peewee import Model, PrimaryKeyField, CharField, IntegerField
class User(Model):
    id = PrimaryKeyField()
    name = CharField()
    age = IntegerField()

    class Meta:
        database = mysql
        db_table = tbl__market_industryOverview+'myuser'

#
# # 删除表
# User.drop_table()
# # 创建表
# User.create_table()
